package boun.swe.bob.service;

import boun.swe.bob.entities.Authority;
import boun.swe.bob.entities.User;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * This controller is used resgister page actions
 */
public class RegisterController extends BaseController {

    /**
     * Shows the page
     *
     * @param httpServletRequest http request
     * @param httpServletResponse http response
     * @return page
     */
    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView showPage(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        return new ModelAndView("register");
    }

    /**
     * Handles HTTP POST action
     *
     * @param httpServletRequest http request
     * @param httpServletResponse http response
     * @return the result message
     */
    @RequestMapping(method = RequestMethod.POST)
    public ModelAndView register(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        Map<String, Object> model = Maps.newHashMap();
        String viewMessage = "";

        String username = httpServletRequest.getParameter("username");
        String password = httpServletRequest.getParameter("password");
        String repassword = httpServletRequest.getParameter("repassword");
        String name = httpServletRequest.getParameter("name");
        String surname = httpServletRequest.getParameter("surname");
        String selfDefinition = httpServletRequest.getParameter("self_definition");
        String userType = httpServletRequest.getParameter("user_type");




        viewMessage = validateForm(username, password, repassword, name, surname);
        boolean validForm = Strings.isNullOrEmpty(viewMessage);

        if(validForm) {
            if(userDao.findByUsername(username) == null) {
                Authority userAuthoriy = new Authority();
                userAuthoriy.setUsername(username);
                userAuthoriy.setAuthority("ROLE_USER");
                userAuthoriy.setUserType(userType);
                authorityDao.save(userAuthoriy);
                User user = new User();
                user.setUsername(username);
                user.setPassword(userDao.createMd5Password(password));
                user.setEnabled(0);
                user.setName(name);
                user.setSurname(surname);
                user.setSelfDefinition(selfDefinition);
                userDao.save(user);
                viewMessage = "Registered succesfully, wait for being approved by admin to log into system...";
            } else {
                putComingValuesToResponse(model, username, name, surname, selfDefinition);
                viewMessage = "Email already exists...";    
            }
        } else {
            putComingValuesToResponse(model, username, name, surname, selfDefinition);
        }

        model.put("message", viewMessage);
        return new ModelAndView("register", "model", model);
    }


    /**
     * Validates the registration form
     *
     * @param username username
     * @param password password
     * @param repassword re-typed password
     * @param name name
     * @param surname surname
     * @return error message string
     */
    private String validateForm(String username, String password, String repassword, String name, String surname){
        String msg = "";
        int errorFiledCount = 0;

        if(Strings.isNullOrEmpty(username)) {
            msg = msg.concat(", Email");
            errorFiledCount++;
        }
        if(Strings.isNullOrEmpty(password)) {
            msg = msg.concat(", Password");
            errorFiledCount++;
        }
        if(Strings.isNullOrEmpty(repassword)) {
            msg = msg.concat(", Repassword");
            errorFiledCount++;
        }
        if(Strings.isNullOrEmpty(name)) {
            msg = msg.concat(", Name");
            errorFiledCount++;
        }
        if(Strings.isNullOrEmpty(surname)) {
            msg = msg.concat(", Surname");
            errorFiledCount++;
        }

        if(!Strings.isNullOrEmpty(msg)){
            String filedStr = errorFiledCount > 1 ? " fields are" : " field is";
            msg = msg.substring(2).concat(filedStr + " empty...");
        } else {
            if(!password.equals(repassword)){
                msg = "Passwords are not same...";
            }
        }
        return msg;
    }

    /**
     * Puts the values into Http response
     *
     * @param model object model
     * @param username username
     * @param name name
     * @param surname surname
     * @param definition define yourself area
     * @return object model
     */
    private Map<String, Object> putComingValuesToResponse(Map<String, Object> model, String username, String name, String surname, String definition){
        model.put("username", username);
        model.put("name", name);
        model.put("surname", surname);
        model.put("definition", definition);
        return model;
    }

}
